import { NotFound, NoAccess } from '@/components/assist'
import DefaultLayout from '@/layouts/defaultLayout'
import { arrayFlat } from '@/utils';
import { lazy } from 'react';
import { Navigate, RouteObject, useLocation } from 'react-router-dom'
const HomePage = lazy(() => import('@/pages/home/home.page'));

// 路由枚举
export enum RoutePathEnum {
    AnyPage = '*',
    RootPage = '/',
    NoAccessPage = '/no-access',
    NotFoundPage = '/not-found',
    LoginPage = '/login',
    LayoutPage = '/layout',
    HomePage = '/layout/home',
    PermissionPage = '/layout/permission',
    PermissionMenuPage = '/layout/permission/menu',
    PermissionRolePage = '/layout/permission/role',
}

// 路由表
export const localRouteList: RouteObject[] = [
    {
        path: RoutePathEnum.LayoutPage,
        element: <DefaultLayout />,
        children: [
            {
                path: RoutePathEnum.HomePage,
                element: <HomePage />,
            },
            {
                path: RoutePathEnum.PermissionMenuPage,
                element: <div>菜单页面</div>,
            },
            {
                path: RoutePathEnum.PermissionRolePage,
                element: <div>角色页面</div>,
            }
        ],
    },
    {
        path: RoutePathEnum.LoginPage,
        element: <div>Login页面</div>,
    },
    {
        path: RoutePathEnum.RootPage,
        element: <Navigate to={RoutePathEnum.HomePage} />,
    },
    {
        path: RoutePathEnum.NoAccessPage,
        element: <NoAccess />,
    },
    {
        path: RoutePathEnum.NotFoundPage,
        element: <NotFound />,
    },
    {
        path: RoutePathEnum.AnyPage,
        element: <RouteCheck />,
    },
]

// 路由验证（无权限或者页面不存在）
function RouteCheck () {
    const { pathname = '' } = useLocation()
    const newLocalRouteList = arrayFlat(localRouteList) as RouteObject[]
    const index = newLocalRouteList.findIndex(item => {
        return item.path === pathname
    })
    return index === -1 ? <NotFound /> : <NoAccess />
}

// 路由白名单（不受权限控制）
const _routeWhiteList: string[] = [RoutePathEnum.HomePage]
export const routeWhiteList: string[] = localRouteList.map((item) => item.path!).concat(_routeWhiteList)
